import { message } from 'antd';

/**
 * 通知类型枚举
 * 定义系统支持的所有通知类型
 */
export enum NotificationType {
  SUCCESS = 'success',
  ERROR = 'error',
  WARNING = 'warning',
  INFO = 'info'
}

/**
 * 通知配置接口
 * 定义通知的可选配置项
 */
interface NotificationConfig {
  duration?: number;
  placement?: 'top' | 'bottom' | 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight';
  onClose?: () => void;
}

/**
 * 默认通知配置
 */
const defaultConfig: NotificationConfig = {
  duration: 3,
  placement: 'top'
};

/**
 * 统一的消息通知服务
 * 提供一致的消息提示功能，简化组件中的消息处理逻辑
 * 支持多种通知类型和配置选项，实现优雅降级
 */
export class NotificationService {
  private messageApi: any | null = null;

  /**
 * 设置 messageApi 实例
 * 与Ant Design的App.useApp()集成
 * @param api messageApi实例
 */
  setMessageApi(api: any): void {
    this.messageApi = api;
  }

  /**
   * 显示通知消息
   * 内部方法，提供消息显示的核心逻辑
   * @param type 通知类型
   * @param content 通知内容
   * @param config 通知配置
   */
  private notify(type: NotificationType, content: string, config: NotificationConfig = {}): void {
    const mergedConfig = { ...defaultConfig, ...config };
    // Ensure a unique key so we can programmatically replace/destroy messages if needed
    const key = (config as any).key || `notif_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;

    // 优先使用 app-scoped messageApi（支持 open({...})），避免静态调用警告
    if (this.messageApi) {
      try {
        // If the messageApi provides an `open` function (App.useApp()), use the object form
        if (typeof this.messageApi.open === 'function') {
          this.messageApi.open({
            type: type as any,
            content,
            duration: mergedConfig.duration,
            key,
            onClose: mergedConfig.onClose,
            // Antd's app message uses `closable`/`closeIcon` in some versions; `closable` is a safe option
          });
          return;
        }

        // Fallback: if messageApi has direct helpers like error/success that accept (content, duration)
        if (typeof this.messageApi[type] === 'function') {
          try {
            // Some implementations expect (content, duration)
            this.messageApi[type](content, mergedConfig.duration);
            return;
          } catch (e) {
            // Fall through to next fallback
          }
        }
      } catch (e) {
        // If using messageApi failed for any reason, fall back to global/static message below
        console.error('messageApi call failed', e);
      }
    }

    // 最后降级到静态 message（来自 antd package）或简单 alert/console
    try {
      if (message && typeof message.open === 'function') {
        message.open({ type: type as any, content, duration: mergedConfig.duration, key, onClose: mergedConfig.onClose });
        return;
      }
    } catch (e) {
      // continue to legacy fallbacks
    }

    // 最保守的降级处理：alert 或 console
    if (type === NotificationType.ERROR || type === NotificationType.WARNING) {
      window.alert(`${type === NotificationType.ERROR ? '错误' : '警告'}: ${content}`);
    } else {
      console.log(`${type}: ${content}`);
    }
  }

  /**
   * 显示成功消息
   * @param content 消息内容
   * @param config 通知配置
   */
  success(content: string, config: NotificationConfig = {}): void {
    this.notify(NotificationType.SUCCESS, content, config);
  }

  /**
   * 显示错误消息
   * 默认显示时间更长，便于用户查看
   * @param content 消息内容
   * @param config 通知配置
   */
  error(content: string, config: NotificationConfig = {}): void {
    // 增加错误日志记录
    console.error(`[Notification] Error: ${content}`);
    this.notify(NotificationType.ERROR, content, { ...config, duration: config.duration || 5 });
  }

  /**
   * 显示警告消息
   * @param content 消息内容
   * @param config 通知配置
   */
  warning(content: string, config: NotificationConfig = {}): void {
    this.notify(NotificationType.WARNING, content, config);
  }

  /**
   * 显示信息消息
   * @param content 消息内容
   * @param config 通知配置
   */
  info(content: string, config: NotificationConfig = {}): void {
    this.notify(NotificationType.INFO, content, config);
  }

  /**
   * 关闭所有消息
   */
  closeAll(): void {
    if (this.messageApi) {
      this.messageApi.destroy();
    } else if (message) {
      message.destroy();
    }
  }
}

/**
 * 创建并导出默认的通知服务实例
 */
export const notificationService = new NotificationService();

export default notificationService;